<?php
declare (strict_types=1);

namespace app\command;

use app\admin\model\MessageTemplate;
use app\home\model\AmountLog;
use app\home\model\Config;
use app\home\model\IntegralLog;
use app\home\model\User;
use app\home\model\UserCommission;
use app\home\model\UserPackage;
use app\services\wechat\Offiaccount;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

/**
 * Class Coupon
 * 修改 失效优惠券
 */
class PackageOrder extends Command
{
    protected function configure()
    {
        $this->setName('packageorder')->setDescription('PackageOrder');
    }

    /**
     * execute()方法 就是 运行该命令行类的时候要执行的具体业务逻辑代码
     */
    protected function execute(Input $input, Output $output)
    {
        for ($i=0;$i<3;$i++) {
            $packageOrderModel = new \app\home\model\PackageOrder();
            $userModel = new User();
            $list = $packageOrderModel
                ->where(['pay_status' => 1])
                ->select()->toArray();
            $offiaccount = new Offiaccount();
            foreach ($list as $value) {
                $value['sn_order'] = $value['order_sn'];
                $userInfo = $userModel->where(['id' => $value['uid']])->find();
                if ($value['pay_type'] == 7) {
                    $rechargeInfo = $offiaccount->orderquery($value);

                    if ($rechargeInfo['return_code'] == 'SUCCESS') {
                        if ($rechargeInfo['trade_state'] == 'SUCCESS') {
                            if ($rechargeInfo['trade_state'] == 'SUCCESS') {

                                try {
                                    $userModel->startTrans();
                                    switch ($value['pay_type']) {
                                        case 7:
                                            $payMethod = 1;
                                            $pay_type = 1;
                                            $payName = '微信';
                                            $operate_type = 16;
                                            break;
                                    }
                                    $AmountLogData = [  // 金额扣除记录
                                        'uid' => $value['uid'],
                                        'amount' => $value['price'],
                                        'create_time' => time(),
                                        'operate_type' => $operate_type,
                                        'pay_type' => $pay_type,
                                        'pay_method' => $payMethod,
                                        'order_id' => $value['id'],
                                        'ratio' => 1,
                                        'type' => 2,
                                        'staff_id' => $value['staff_id'],
                                        'store_id' => $value['store_id'],
                                        'order_sn' => $value['order_sn'],
                                    ];
                                    $amountLogModel = new AmountLog();
                                    $amountLogModel->insert($AmountLogData);
                                    if ($value['store_id']> 0){
                                        $storeModel = new \app\merchant\model\Store();
                                        $storeModel->where(['id' => $value['store_id']])->inc('package_amount',(float)$value['price'])->update();
                                    }
                                    $integralLogModel = new IntegralLog();
                                    $userModel = new \app\home\model\User();
                                    $distribution_level = Config::getConfigValue('distribution_level');
                                    $firstCommissionData = [];
                                    $secondCommissionData = [];
                                    if ($distribution_level > 0) {
                                        if ($userInfo['pid'] > 0) {
                                            $first_commission = Config::getConfigValue('first_commission');
                                            if ($first_commission > 0) {
                                                $pUserInfo = $userModel->where(['id' => $userInfo['pid']])->find();
                                                $userCommissionModel = new UserCommission();
                                                $firstCommissionData = [
                                                    'trigger_uid' => $userInfo['id'],
                                                    'receive_uid' => $userInfo['pid'],
                                                    'level' => 1,
                                                    'amount' => bcdiv((string)bcmul($value['price'], (string)$first_commission, 2), '100', 2),
                                                    'ratio' => $first_commission,
                                                    'order_id' => $value['id'],
                                                    'create_time' => time(),
                                                    'type' => 2,
                                                ];
                                                $userCommissionModel->insert($firstCommissionData);
                                                $userModel->where(['id' => $userInfo['pid']])
                                                    ->inc('total_commission', (float)bcdiv(bcmul((string)$first_commission, (string)$value['price'], 2), '100', 2))
                                                    ->inc('surplus_commission', (float)bcdiv(bcmul((string)$first_commission, (string)$value['price'], 2), '100', 2))
                                                    ->update();
                                            }
                                            if ($distribution_level >= 2) {

                                                $second_commission = Config::getConfigValue('second_commission');
                                                if ($pUserInfo['pid'] > 0 && $second_commission > 0) {
                                                    $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                                                    $userCommissionModel = new UserCommission();
                                                    $secondCommissionData = [
                                                        'trigger_uid' => $userInfo['id'],
                                                        'receive_uid' => $pUserInfo['pid'],
                                                        'level' => 2,
                                                        'amount' => bcdiv(bcmul((string)$value['price'], (string)$second_commission, 2), '100', 2),
                                                        'ratio' => $second_commission,
                                                        'order_id' => $value['id'],
                                                        'create_time' => time(),
                                                        'type' => 2,
                                                    ];
                                                    $userCommissionModel->insert();
                                                    $userModel->where(['id' => $pUserInfo['pid']])
                                                        ->inc('total_commission', (float)bcdiv(bcmul((string)$second_commission, $value['price'], 2), '100', 2))
                                                        ->inc('surplus_commission', (float)bcdiv(bcmul((string)$second_commission, $value['price'], 2), '100', 2))
                                                        ->update();
                                                }
                                            }
                                        }
                                    }
                                    $userModel->where(['id' => $userInfo['id']])
                                        ->inc('consumption_amount', (float)$value['price'])
                                        ->inc('package_num')
                                        ->inc('integral', (float)$value['get_integral'])
                                        ->inc('surplus_integral', (float)$value['get_integral'])
                                        ->update();
                                    $userModel->updateUserLevel($userInfo['id'], bcadd($userInfo['consumption_amount'], $value['price'], 2));
                                    $integralLogData = [ // 积分变化
                                        'num' => $value['get_integral'],
                                        'deduction_ratio' => $value['get_integral_ratio'],
                                        'type' => 1,
                                        'mode_type' => 5,
                                        'order_id' => $value['id'],
                                        'create_time' => time(),
                                        'uid' => $userInfo['id'],
                                    ];
                                    $integralLogModel->insert($integralLogData);
                                    $userPackageModel = new UserPackage();
                                    $packageModel = new \app\home\model\Package();
                                    $packageInfo = $packageModel->where(['id' => $value['package_id']])->find();

                                    $userPackageData = [
                                        'package_id' => $value['package_id'],
                                        'uid' => $userInfo['id'],
                                        'num' => $packageInfo['number'] + $packageInfo['give_number'],
                                        'total_num' => $packageInfo['number'] + $packageInfo['give_number'],
                                        'create_time' => time(),
                                        'order_id' => $value['id'],
                                    ];
                                    $userPackageModel->insert($userPackageData);
                                    $packageModel->where(['id' => $value['package_id']])->inc('sales_volume')->inc('sales_amount', (float)$value['price'])->update();
                                    $packageOrderModel->where(['id' => $value['id']])->update(['status' => 3, 'pay_status' => 2]);
                                    $userModel->commit();
                                } catch (\Exception $exception) {
                                    $userModel->rollback();
                                }
                                $messageModel = new MessageTemplate();
                                if ($firstCommissionData) { // 一级分佣
                                    $messageModel->sendMessage($pUserInfo['openid'], [
                                        'thing2' => ['value' => '直推佣金'],
                                        'amount8' => ['value' => $firstCommissionData['amount']],
                                        'amount6' => ['value' => bcadd((string)$pUserInfo['surplus_commission'], (string)$firstCommissionData['amount'], 2)],
                                        'time4' => ['value' => date('Y-m-d H:i:s')]], 'commission_add'); //
                                }
                                if ($secondCommissionData) { // 一级分佣
                                    $messageModel->sendMessage($ppUserInfo['openid'], [
                                        'thing2' => ['value' => '间推佣金'],
                                        'amount8' => ['value' => $secondCommissionData['amount']],
                                        'amount6' => ['value' => bcadd((string)$ppUserInfo['surplus_commission'], (string)$secondCommissionData['amount'], 2)],
                                        'time4' => ['value' => date('Y-m-d H:i')],
                                    ], 'commission_add'); //
                                }


                                if ($value['get_integral']) {  // 积分变动
                                    $messageModel->sendMessage($userInfo['openid'], [
                                        'thing2' => ['value' => '积分'],
                                        'amount2' => ['value' => $value['get_integral'] . '分'],
                                        'amount6' => ['value' => bcadd((string)$userInfo['surplus_integral'], (string)$value['get_integral'], 2) . '分'],
                                        'time4' => ['value' => date('Y-m-d H:i')],
                                    ], 'integral_add'); //
                                }
                                $messageModel->sendMessage($userInfo['openid'], [
                                    'thing2' => ['value' => $packageInfo['name']],
                                    'amount3' => ['value' => $packageInfo['price']],
                                    'thing9' => ['value' => date('Y-m-d  H:i:s')]

                                ], 'buy_package'); // 购买套餐卡
                            } elseif ($rechargeInfo['trade_state'] == 'CLOSED' || $rechargeInfo['trade_state'] == 'PAYERROR' || $rechargeInfo['trade_state'] == 'NOTPAY' || $rechargeInfo['trade_state'] == 'REFUND') {
                                if (time() - $value['pay_time'] > 120) {
                                    $packageOrderModel->where(['id' => $value['id']])->update(['pay_status' => 3]);
                                }
                            }
                        }
                    }
                } elseif ($value['pay_type'] == 8) {
                    $AliOffiaccount = new \app\services\alipay\Offiaccount();
                    $aliOrderInfo = $AliOffiaccount->orderquery($value);
                    if ($aliOrderInfo['alipay_trade_query_response']['code'] == 10000) {
                        if ($aliOrderInfo['alipay_trade_query_response']['trade_status'] == 'TRADE_SUCCESS') {
                            try {
                                switch ($value['pay_type']) {

                                    case 8:
                                        $payMethod = 2;
                                        $pay_type = 1;
                                        $payName = '微信';
                                        $operate_type = 17;
                                }
                                $AmountLogData = [  // 金额扣除记录
                                    'uid' => $value['uid'],
                                    'amount' => $value['price'],
                                    'create_time' => time(),
                                    'operate_type' => $operate_type,
                                    'pay_type' => $pay_type,
                                    'pay_method' => $payMethod,
                                    'order_id' => $value['id'],
                                    'ratio' => 1,
                                    'type' => 2,
                                    'staff_id' => $value['staff_id'],
                                    'store_id' => $value['store_id'],
                                    'order_sn' => $value['order_sn'],
                                ];
                                $userModel->startTrans();
                                if ($value['pay_type'] == 1) {
                                    $userModel->where(['id' => $userInfo['id']])
                                        ->dec('balance', (float)$value['price'])->update();
                                }
                                $amountLogModel = new AmountLog();
                                $amountLogModel->insert($AmountLogData);
                                if ($value['store_id']> 0){
                                    $storeModel = new \app\merchant\model\Store();
                                    $storeModel->where(['id' => $value['store_id']])->inc('package_amount',(float) $value['price'])->update();
                                }
                                $integralLogModel = new IntegralLog();
                                $userModel = new \app\home\model\User();
                                $distribution_level = Config::getConfigValue('distribution_level');
                                $firstCommissionData = [];
                                $secondCommissionData = [];
                                if ($distribution_level > 0) {
                                    if ($userInfo['pid'] > 0) {
                                        $first_commission = Config::getConfigValue('first_commission');
                                        if ($first_commission > 0) {
                                            $pUserInfo = $userModel->where(['id' => $userInfo['pid']])->find();
                                            $userCommissionModel = new UserCommission();
                                            $firstCommissionData = [
                                                'trigger_uid' => $userInfo['id'],
                                                'receive_uid' => $userInfo['pid'],
                                                'level' => 1,
                                                'amount' => bcdiv(bcmul((string)$value['price'], (string)$first_commission, 2), '100', 2),
                                                'ratio' => $first_commission,
                                                'order_id' => $value['id'],
                                                'create_time' => time(),
                                                'type' => 2,
                                            ];
                                            $userCommissionModel->insert($firstCommissionData);
                                            $userModel->where(['id' => $userInfo['pid']])
                                                ->inc('total_commission', (float)bcdiv(bcmul((string)$first_commission, (string)$value['price'], 2), '100', 2))
                                                ->inc('surplus_commission', (float)bcdiv(bcmul((string)$first_commission, $value['price'], 2), '100', 2))
                                                ->update();
                                        }
                                        if ($distribution_level >= 2) {
                                            $second_commission = Config::getConfigValue('second_commission');
                                            if ($pUserInfo['pid'] > 0 && $second_commission > 0) {
                                                $ppUserInfo = $userModel->where(['id' => $pUserInfo['pid']])->find();
                                                $userCommissionModel = new UserCommission();
                                                $secondCommissionData = [
                                                    'trigger_uid' => $userInfo['id'],
                                                    'receive_uid' => $pUserInfo['pid'],
                                                    'level' => 2,
                                                    'amount' => bcdiv(bcmul((string)$value['price'], (string)$second_commission, 2), '100', 2),
                                                    'ratio' => $second_commission,
                                                    'order_id' => $value['id'],
                                                    'create_time' => time(),
                                                    'type' => 2,
                                                ];
                                                $userCommissionModel->insert();
                                                $userModel->where(['id' => $pUserInfo['pid']])
                                                    ->inc('total_commission', (float)bcdiv(bcmul((string)$second_commission, $value['price'], 2), '100', 2))
                                                    ->inc('surplus_commission', (float)bcdiv(bcmul((string)$second_commission, $value['price'], 2), '100', 2))
                                                    ->update();
                                            }
                                        }
                                    }
                                }
                                $userModel->where(['id' => $userInfo['id']])
                                    ->inc('consumption_amount', (float)$value['price'])
                                    ->inc('package_num')
                                    ->inc('integral', (float)$value['get_integral'])
                                    ->inc('surplus_integral', (float)$value['get_integral'])
                                    ->update();
                                $userModel->updateUserLevel($userInfo['id'], bcadd($userInfo['consumption_amount'], $value['price'], 2));
                                if ($value['get_integral']) {
                                    $integralLogData = [ // 积分变化
                                        'num' => $value['get_integral'],
                                        'deduction_ratio' => $value['get_integral_ratio'],
                                        'type' => 1,
                                        'mode_type' => 5,
                                        'order_id' => $value['id'],
                                        'create_time' => time(),
                                        'uid' => $userInfo['id'],
                                    ];
                                    $integralLogModel->insert($integralLogData);
                                }

                                $userPackageModel = new UserPackage();
                                $packageModel = new \app\home\model\Package();
                                $packageInfo = $packageModel->where(['id' => $value['package_id']])->find();

                                $userPackageData = [
                                    'package_id' => $value['package_id'],
                                    'uid' => $userInfo['id'],
                                    'num' => $packageInfo['number'] + $packageInfo['give_number'],
                                    'total_num' => $packageInfo['number'] + $packageInfo['give_number'],
                                    'create_time' => time(),
                                    'order_id' => $value['id'],
                                ];
                                $userPackageModel->insert($userPackageData);
                                $packageModel->where(['id' => $value['package_id']])->inc('sales_volume')->inc('sales_amount', (float)$value['price'])->update();
                                $packageOrderModel->where(['id' => $value['id']])->update(['status' => 3, 'pay_status' => 2, 'pay_time' => time()]);
                                $userModel->commit();
                            } catch (\Exception $exception) {
                                $userModel->rollback();
                            }
                            $messageModel = new MessageTemplate();
                            if ($firstCommissionData) { // 一级分佣
                                $messageModel->sendMessage($pUserInfo['openid'], [
                                    'thing2' => ['value' => '直推佣金'],
                                    'amount8' => ['value' => $firstCommissionData['amount']],
                                    'amount6' => ['value' => bcadd((string)$pUserInfo['surplus_commission'], (string)$firstCommissionData['amount'], 2)],
                                    'time4' => ['value' => date('Y-m-d H:i')]], 'commission_add'); //
                            }
                            if ($secondCommissionData) { // 一级分佣
                                $messageModel->sendMessage($ppUserInfo['openid'], [
                                    'thing2' => ['value' => '间推佣金'],
                                    'amount8' => ['value' => $secondCommissionData['amount']],
                                    'amount6' => ['value' => bcadd((string)$ppUserInfo['surplus_commission'], (string)$secondCommissionData['amount'], 2)],
                                    'time4' => ['value' => date('Y-m-d H:i')],
                                ], 'commission_add'); //
                            }

                            if ($value['get_integral']) {  // 积分变动
                                $messageModel->sendMessage($userInfo['openid'], [
                                    'thing2' => ['value' => '积分'],
                                    'amount2' => ['value' => $value['get_integral'] . '分'],
                                    'amount6' => ['value' => bcadd((string)$userInfo['surplus_integral'], (string)$value['get_integral'], 2) . '分'],
                                    'time4' => ['value' => date('Y-m-d H:i')],
                                ], 'integral_add'); //
                            }
                            $messageModel->sendMessage($userInfo['openid'], [
                                'thing2' => ['value' => $packageInfo['name']],
                                'amount3' => ['value' => $packageInfo['price']],
                                'thing9' => ['value' => date('Y-m-d  H:i:s')]

                            ], 'buy_package'); // 购买套餐卡
                        } elseif ($aliOrderInfo['alipay_trade_query_response']['trade_status'] == 'TRADE_CLOSED') {
                            $packageOrderModel->where(['id' => $value['id']])->update(['pay_status' => 3]);
                        }

                    }
                }
            }
            sleep(20);
        }

    }

}